package com.hongshan.wallet.util

import android.content.Intent
import com.hongshan.wallet.Constant

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.util
 * @author   : zhangxx
 * @date     : 2019/4/2
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
object InjectParams {
    fun inject(intent: Intent, vararg obj: Any) {
        obj.forEach { o ->
            val fields = o.javaClass.declaredFields
            fields.filter {
                it.isAccessible = true
                it.isAnnotationPresent(AutoInject::class.java)
            }.forEach { field ->
                val annotations = field.getAnnotation(AutoInject::class.java)
                var key = annotations.value
                if (key == "") {
                    key = field.name
                }
                field.set(
                    o, when {
                        field.type.isAssignableFrom(Int::class.java) -> intent.getIntExtra(key,0)
                        field.type.isAssignableFrom(Long::class.java) -> intent.getLongExtra(key,0)
                        field.type.isAssignableFrom(Double::class.java) -> intent.getDoubleExtra(key,0.0)
                        field.type.isAssignableFrom(Float::class.java) -> intent.getFloatExtra(key,0.0F)
                        field.type.isAssignableFrom(Char::class.java) -> intent.getCharExtra(key,' ')
                        field.type.isAssignableFrom(Boolean::class.java) -> intent.getBooleanExtra(key,false)
                        field.type.isAssignableFrom(CharSequence::class.java) -> intent.getCharSequenceExtra(key)
                        else -> Constant.gson.fromJson(intent.getStringExtra(key),field.type)
                    }
                )
//            }
            }
        }
    }
}